package org.jaronsource.framework.core.web.taglib;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.jaronsource.framework.core.dao.support.ICommonDao;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class QueryTag extends TagSupport {

	private static final long serialVersionUID = 8077035430436042219L;

	protected String jpql;
	protected String var;
	protected Map<String, Object> params = new HashMap<String, Object>();

	public String getJpql() {
		return jpql;
	}
	
	public void setJpql( String jpql ) {
		this.jpql = jpql;
	}

	public String getVar() {
		return var;
	}

	public void setVar( String var ) {
		this.var = var;
	}

	public int doStartTag() throws JspException {
		params.clear();
		return EVAL_BODY_INCLUDE;
	}

	public void addParam( String name, Object value ) {
		params.put( name, value );
	}

	public int doEndTag() throws JspException {
		
		ServletContext sc = pageContext.getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext( sc );

		ICommonDao commonDao = wac.getBean( ICommonDao.class );

		List<Object> result = commonDao.query( jpql, params );
		pageContext.setAttribute( var, result );
		return SKIP_BODY;
	}
	
}